import * as vscode from 'vscode';
import * as path from 'path';
import { MavenUtils } from './mavenUtils';

export class MavenRunner {
    private mavenUtils: MavenUtils;
    private lastUsedGoals: string[] = ['clean', 'install', 'compile', 'test', 'package'];
    
    constructor() {
        this.mavenUtils = new MavenUtils();
    }
    
    /**
     * 运行Maven目标
     * @param forRoot 是否在根模块运行
     */
    public async runMavenGoal(forRoot: boolean): Promise<void> {
        const editor = vscode.window.activeTextEditor;
        let pomPath: string | undefined;
        
        // 获取POM文件路径
        if (editor && editor.document.fileName.endsWith('pom.xml')) {
            pomPath = editor.document.fileName;
        } else {
            // 如果当前编辑器不是POM文件，让用户选择一个POM文件
            const pomFiles = await this.mavenUtils.findAllPomFiles();
            if (pomFiles.length === 0) {
                vscode.window.showErrorMessage('找不到POM文件');
                return;
            }
            
            if (pomFiles.length === 1) {
                pomPath = pomFiles[0].fsPath;
            } else {
                const selectedPom = await vscode.window.showQuickPick(
                    pomFiles.map(file => ({
                        label: path.basename(path.dirname(file.fsPath)),
                        description: file.fsPath
                    })),
                    { placeHolder: '选择要运行Maven目标的模块' }
                );
                
                if (!selectedPom) {
                    return;
                }
                
                pomPath = selectedPom.description;
            }
        }
        
        if (!pomPath) {
            return;
        }
        
        // 如果需要使用根模块
        if (forRoot) {
            const rootPomPath = await this.mavenUtils.findRootPom(pomPath);
            if (rootPomPath) {
                pomPath = rootPomPath;
            } else {
                vscode.window.showWarningMessage('找不到根模块POM，使用当前模块');
            }
        }
        
        // 让用户选择或输入Maven目标
        const goal = await this.selectMavenGoal();
        if (!goal) {
            return;
        }
        
        // 更新最近使用的目标列表
        this.updateLastUsedGoals(goal);
        
        // 在终端中执行Maven命令
        const terminal = vscode.window.createTerminal(`Maven: ${goal}`);
        const mvn = await this.mavenUtils.getMavenExecutable();
        const modulePath = path.dirname(pomPath);
        
        terminal.sendText(`cd "${modulePath}"`);
        terminal.sendText(`${mvn} ${goal}`);
        terminal.show();
    }
    
    /**
     * 在指定路径运行Maven目标
     * @param pomPath POM文件路径
     * @param goal Maven目标
     */
    public async runMavenGoalOnPath(pomPath: string, goal: string): Promise<void> {
        if (!pomPath) {
            vscode.window.showErrorMessage('未指定POM文件路径');
            return;
        }

        // 更新最近使用的目标列表
        this.updateLastUsedGoals(goal);
        
        // 在终端中执行Maven命令
        const moduleName = path.basename(path.dirname(pomPath));
        const terminal = vscode.window.createTerminal(`Maven: ${moduleName} - ${goal}`);
        const mvn = await this.mavenUtils.getMavenExecutable();
        const modulePath = path.dirname(pomPath);
        
        terminal.sendText(`cd "${modulePath}"`);
        terminal.sendText(`${mvn} ${goal}`);
        terminal.show();
    }
    
    /**
     * 让用户选择Maven目标
     */
    public async selectMavenGoal(): Promise<string | undefined> {
        const commonGoals = [
            '清理并安装 (clean install)',
            '清理并编译 (clean compile)',
            '清理并测试 (clean test)',
            '清理并打包 (clean package)',
            ...this.lastUsedGoals.filter(g => !['clean', 'install', 'compile', 'test', 'package'].includes(g))
                .map(g => `${g}`),
            '自定义目标...'
        ];
        
        const selected = await vscode.window.showQuickPick(commonGoals, {
            placeHolder: '选择Maven目标'
        });
        
        if (!selected) {
            return undefined;
        }
        
        if (selected === '自定义目标...') {
            const customGoal = await vscode.window.showInputBox({
                placeHolder: '输入Maven目标 (例如: clean install -DskipTests)',
                prompt: '输入要执行的Maven目标'
            });
            
            return customGoal;
        } else {
            // 从显示文本中提取实际命令
            const match = selected.match(/\((.*?)\)/);
            return match ? match[1] : selected;
        }
    }
    
    /**
     * 更新最近使用的目标列表
     */
    private updateLastUsedGoals(goal: string): void {
        // 将新目标添加到开头
        this.lastUsedGoals = [goal, ...this.lastUsedGoals.filter(g => g !== goal)];
        
        // 只保留前10个
        if (this.lastUsedGoals.length > 10) {
            this.lastUsedGoals = this.lastUsedGoals.slice(0, 10);
        }
        
        // 可以考虑将此列表保存到全局状态中，以便在扩展重启后保留
    }
    
    /**
     * 调试Maven目标
     * 注意：这需要配置Java调试器，这里只是一个简化示例
     */
    public async debugMavenGoal(_forRoot: boolean): Promise<void> {
        // 使用下划线前缀告诉TypeScript这是一个有意未使用的参数
        // 类似于runMavenGoal，但添加调试参数
        // 例如: mvnDebug而不是mvn，或添加-Dmaven.surefire.debug
        vscode.window.showInformationMessage('Maven调试功能正在开发中');
    }
}
